<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>超时与取消请求</title>
</head>
<body>
    <button>发送请求</button>
    <button>取消请求</button>

    <script>
        const buttons = document.querySelectorAll('button')

        let xhr 
        buttons[0].onclick = ()=>{
            xhr  = new XMLHttpRequest()
            xhr.open('get','http://localhost:9812/delay-server')
        


        // 指定超时时间 应用中一般会指定为20--30s
        xhr.timeout = 20000 // ms为单位
        // 专门监视超时错误
        xhr.ontimeout = ()=>{
            alert('超时错误！')
        }

        xhr.onreadystatechange = ()=>{
            console.log(xhr.readyState,xhr.status,xhr.responseText);
            if(xhr.readyState === 4){
                console.log('----',xhr.status,xhr.responseText);
            }
        }
        xhr.send()
    }

    buttons[1].onclick = ()=>{
        // 中断请求
        xhr.abort()
        console.log('中断请求');
    }




    </script>
</body>
</html>